<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Statistics</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Le styles -->
    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
    <style type="text/css">
      body {
      background-color: #eeeeee;
        padding-top: 0px;
        padding-bottom: 40px;
      }
      .sidebar-nav {
        padding: 9px 0;
      }
     .table {
		 width: 700px;
	 }
     /* .table tbody tr:hover td,
		.table tbody tr:hover th {
    		background-color: inherit; */
		}
    </style>
    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script src="js/bgraph.js"></script>
    <script>
var endpoint = "http://data.aalto.fi/sparql";
if(window.location.href.indexOf("?endpoint=")>1) {
	endpoint = decodeURIComponent(window.location.href.substr(window.location.href.indexOf("?endpoint=")+10))
}

//var openAc =  "http://data.open.ac.uk/query";
//var endpointb = "http://data.uni-muenster.de/sparql";
//var endpoint = "http://data.aalto.fi/sparql";

var bgraph = new BGraph();
var prefix = bgraph.getPrefixes();
google.load("visualization", "1", {packages:["corechart"]});

$(document).ready(function() {

// Number of literals
var qn = "SELECT (COUNT(?o) as ?no) WHERE { ?s ?p ?o . FILTER isLiteral(?o) }";
// Number of empty literals
var qx = "SELECT (COUNT(?o) AS ?no) WHERE { ?s ?p ?o . FILTER isLiteral(?o) FILTER(strlen(str(?o))<1) }";
// Number of subject without type
var q0 = "SELECT (COUNT(?s) AS ?no) WHERE { ?s ?p ?o . FILTER NOT EXISTS { ?s a ?type }}"

var pDeviation = "SELECT ?class (min(?count) as ?min) (avg(?count) as ?avg) (max(?count) as ?max) { {SELECT DISTINCT ?class (count(?p) as ?count)   { ?s ?p ?o . ?s a ?class . } GROUP BY ?s ?class } } GROUP BY ?class";

// total number of distinct classes and instances with a type
var qciCount = prefix+"SELECT (COUNT(?instance) AS ?iCount) (COUNT(distinct ?type) AS ?cCount) WHERE { ?instance a ?type }";

//var qtotCount = prefix+"SELECT (COUNT(DISTINCT ?s) AS ?sdCount) (COUNT(DISTINCT ?p) AS ?pdCount) (COUNT(DISTINCT ?o) AS ?odCount) WHERE { ?s ?p ?o  }";

//total number of triples
var qtCount = prefix+"SELECT (COUNT(*) AS ?tCount)  WHERE { ?s ?p ?o  }";

//total number of distinct subject nodes
//var qsdCount = prefix+"SELECT (COUNT(DISTINCT ?s) AS ?sdCount) WHERE { ?s ?p ?o }";
// total number distinct predicates
var qpdCount = prefix+"SELECT (COUNT(DISTINCT ?p) AS ?pdCount) WHERE { ?s ?p ?o }"; 
//total number of distinct subject nodes
//var qodCount = prefix+"SELECT (COUNT(DISTINCT ?o) AS ?odCount) WHERE { ?s ?p ?o }";

// Total number of distinct literals
var qlitCount = prefix+"SELECT (COUNT(DISTINCT ?o) AS ?dlitCount) (COUNT(?o) AS ?litCount) WHERE { ?s a ?type . ?s ?p ?o  filter(!isLiteral(?o)) }";
// Number of recurring literals
var ql = "SELECT DISTINCT (COUNT(?o) as ?no) WHERE { ?s ?p ?o . FILTER isLiteral(?o) } GROUP BY ?o HAVING(?no > 1)";
// Number of literals by domain
var qlitDom = prefix+"SELECT ?localName (COUNT(?p) AS ?count) WHERE { ?s a ?type . ?s ?p ?o . FILTER isLiteral(?o) BIND(STR(?p) AS ?pn) BIND(REPLACE(?pn, '[^#|^/]*$', '') AS ?domain) BIND(STRAFTER(?pn,?domain) AS ?localName) } GROUP BY ?domain ?localName ORDER BY ?count";

// predicate domain names vs. number of triples
var q7 = prefix+"SELECT str(?domain) count(?s) WHERE { ?s ?p ?o . BIND(afn:namespace(?p) AS ?domain) } GROUP BY ?domain";
// subject domain names vs. number of distinct subjects
var q8 = prefix+"SELECT str(?domain) count(DISTINCT ?s) WHERE { ?s ?p ?o . BIND(afn:namespace(?s) AS ?domain) } GROUP BY ?domain";
// properties and number of triples
var q9 = prefix+"SELECT ?p (COUNT(?s) AS ?count ) { ?s ?p ?o } GROUP BY ?p ORDER BY ?count";
// Type of literals
var q10 = prefix+"SELECT ?type (count(?literal) as ?count)  WHERE { ?any ?property ?literal . FILTER isLiteral(?literal) BIND(datatype(?literal) as ?type) BIND(afn:namespace(?type) as ?namespace) } GROUP BY ?type ORDER BY ?count";

var ajaxTime;

//var q4 = prefix+"SELECT ?class (COUNT(?s) AS ?count) { ?s a ?class } GROUP BY ?class ORDER BY ?count";
//var q5 = prefix+"SELECT srt(?p) (COUNT(DISTINCT ?s ) AS ?Subjects ) { ?s ?p ?o } GROUP BY ?p ORDER BY desc(?Subjects)";

function ajaxQuery(q) {
	//return $.ajax({url: endpoint+"?query="+encodeURIComponent(q),format:"json",accept:"application/sparql-results+json"});
	return $.ajax({
        url: endpoint,
        dataType: 'json',
        data: { query: q, format: 'json', Accept: 'application/sparql-results+json'}
    });
}

function plotText(queryString) {
	ajaxTime = new Date().getTime();
	return ajaxQuery(queryString).done(function(data) {
	 console.log(queryString);
	 console.log((new Date().getTime()-ajaxTime)/1000 +" sekuntia");
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
		var vars = data.head.vars;
        data = data.results.bindings;
		
		for(item in data) {
            for(id in vars) {
                $("#"+vars[id]).html(data[item][vars[id]].value);
            }
		}
		
	} else $("#error").html("No results found");
	});
}

function plotPie(queryString,elem) {
	return ajaxQuery(queryString).done(function(data) {
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
		console.log(data);
		var data = new google.visualization.DataTable(bgraph.SparqlJSON2GoogleJSON(data));
		console.log(data);
		var viz = new google.visualization.PieChart($(elem)[0]);
				
		var options = {
			is3D:true,
			height: 300,
			width:500,
			chartArea:{left:0,top:0},
        	backgroundColor: {fill:"#efefef"},
        	legendTextStyle:{color:"#222", fontSize:9, bold:true},
       		legend:"right",
       		theme:"maximized"
			};
			
		viz.draw(data,options);
		
	}});
}

function plotStacked(queryString,elem) {
	return ajaxQuery(queryString).done(function(data) {
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
				
		var data = new google.visualization.DataTable(bgraph.SparqlJSON2GoogleJSON(data));
		var viz = new google.visualization.ColumnChart($(elem)[0]);
		
		var options = '{"backgroundColor": {"fill":"#efefef"},"height":300,"width":500,"focusTarget":"category","hAxis":{"logScale":true,"useFormatFromData":true},"legend":"right","vAxes":[{"useFormatFromData":true,"viewWindowMode":"pretty"},{"useFormatFromData":true,"viewWindowMode":"pretty"}],"isStacked":true,"animation":{"duration":500},"booleanRole":"certainty"}';
		//var options = '{"backgroundColor": {"fill":"#efefef"},"height":300,"width":500,"hAxis":{"logScale":true,"useFormatFromData":true},"vAxes":[{"useFormatFromData":true,"viewWindowMode":"pretty"},{"useFormatFromData":true,"viewWindowMode":"pretty"}],"animation":{"duration":500},"booleanRole":"certainty","legend":"none","focusTarget":"category","theme":"maximized"}';
	
		options = $.parseJSON(options);
		
		viz.draw(data,options);
		
	}});
}

function plotBar(queryString,elem) {
	return ajaxQuery(queryString).done(function(data) {
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
				
		var data = new google.visualization.DataTable(bgraph.SparqlJSON2GoogleJSON(data));
		var viz = new google.visualization.ColumnChart($(elem)[0]);
		
		var options = '{"backgroundColor": {"fill":"#efefef"},"height":300,"width":500,"hAxis":{"useFormatFromData":true},"vAxes":[{"logScale":true,"useFormatFromData":true,"viewWindowMode":"pretty"},{"useFormatFromData":true,"viewWindowMode":"pretty"}],"animation":{"duration":500},"booleanRole":"certainty","legend":"none","focusTarget":"category","theme":"maximized"}';
	
		options = $.parseJSON(options);
		
		viz.draw(data,options);
		
	}});
}

function plotRadar(queryString,elem) {
	return ajaxQuery(queryString).done(function(data) {
	// data = $.parseJSON(data); // For debugging only
	if(data.results.bindings.length>0) {
				
		var data = new google.visualization.DataTable(bgraph.SparqlJSON2GoogleJSON(data));
	//	var viz = new google.visualization.ChartWrapper($.parseJSON('{"containerId":"","options":{"backgroundColor": {"fill":"#efefef"},"height":300,"width":500,"hAxis":{"useFormatFromData":true,"viewWindowMode":"pretty","viewWindow":{"max":null,"min":null},"minValue":null,"maxValue":null},"title":"","vAxes":[{"useFormatFromData":true,"viewWindowMode":"pretty","viewWindow":{"max":null,"min":null},"minValue":null,"maxValue":null},{"useFormatFromData":true,"viewWindowMode":"pretty","viewWindow":{"max":null,"min":null},"minValue":null,"maxValue":null}],"cht":"rs","booleanRole":"certainty","colors":["#3366CC","#DC3912","#FF9900","#109618","#990099","#0099C6","#DD4477","#66AA00","#B82E2E","#316395","#994499","#22AA99","#AAAA11","#6633CC","#E67300","#8B0707","#651067","#329262","#5574A6","#3B3EAC","#B77322","#16D620","#B91383","#F4359E","#9C5935","#A9C413","#2A778D","#668D1C","#BEA413","#0C5922","#743411"],"chm":"","valuesSuffix":"","chxs":"1NLiterals **","valuesPrefix":"Literals ","min":null,"max":null,"legend":"none"},"state":{},"view":{"columns":[{"calc":"emptyString","sourceColumn":0,"type":"string"},0]},"chartType":"ImageChart"}'));
		var viz = new google.visualization.ImageChart($(elem)[0]);
		var options = '{"containerId":"rlit","hAxis":{"useFormatFromData":true,"viewWindowMode":"pretty"},"vAxes":[{"useFormatFromData":true,"viewWindowMode":"pretty"},{"useFormatFromData":true,"viewWindowMode":"pretty"}],"cht":"rs","booleanRole":"certainty","colors":["#3366CC","#DC3912","#FF9900","#109618","#990099","#0099C6","#DD4477","#66AA00","#B82E2E","#316395","#994499","#22AA99","#AAAA11","#6633CC","#E67300","#8B0707","#651067","#329262","#5574A6","#3B3EAC","#B77322","#16D620","#B91383","#F4359E","#9C5935","#A9C413","#2A778D","#668D1C","#BEA413","#0C5922","#743411"],"backgroundColor":"#cccccc","legend":"none","showValueLabels":true,"valuesSuffix":" literals","chxs":"1N** literals"}';
		options = $.parseJSON(options);
		
		viz.draw(data,options);
		
	}});
}

//plotText(q3,"#preds");
//plotText(q6,"#onodes");
//plotText(q0,"#bnodes");
//plotText(qx,"#elit");
//plotText(qn,"#nlit");

function runQueries() {
	
var q1 = plotText(qciCount);

$.when(q1).done(function () {
	$("#aPop").html(Math.floor($("#iCount").html()/$("#cCount").html()));
	
	plotText(qlitCount).done(function() {
	
	plotText(qpdCount);
	$("#litRe").html((($("#dlitCount").html()/$("#litCount").html())*100).toFixed(1)+"%");
	});
	
	

	
});

//plotText(qtCount);



}

runQueries();


//plotText(qsdCount).done(function() {
//plotText(qpdCount).done(function() {
//plotText(qodCount).done(function() {
//plotText(qlitCount).done(function() {
//})})})});

google.setOnLoadCallback(function() {
plotBar(qlitDom,"#barLit").done(function () {
plotPie(q9,"#pie3").done(function () {
plotStacked(pDeviation,"#barDev");
});
});
//plotPie(q7,"#pie1");
//plotPie(q8,"#pie2");
//plotBar(q10,"#bar1");
//plotRadar(ql,"#rlit");
});

});
</script>
</head>
<body>
<div class="hero-unit" id="stats">
    <h1>Statistics</h1>
    <p>
    <table class="table">
    <thead><tr><th>Average population</th><th>Results</th></tr></thead>
    <tbody>
    <tr><td>Number of distinct classes (C)</td>
        <td id="cCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>    
    <tr><td>Number of instances (I)</td>
        <td id="iCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
    <tr><td><i>Average</i> (I / C)</td>
        <td id="aPop"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
     </tbody>
    </table>
    
    
    <table class="table">
    <thead><tr><th>Literals</th><th>Results</th></tr></thead>
    <tbody>
  <!--  <tr><td>Number of distinct subjects</td>
        <td id="sdCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
    <tr><td>Number of distinct predicates</td>
        <td id="pdCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
    <tr><td>Number of distinct objects</td>
        <td id="odCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr> -->
     <tr><td>Number of literals</td>
        <td id="litCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
     <tr><td>Number of distinct literals</td>
        <td id="dlitCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
     <tr><td><i>Redundancy</i></td>
        <td id="litRe"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
     <tr><td>Number of literals by property</td></tr>
        <tr><td id="barLit"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
          </tbody>
    </table>
    
    <table class="table">
    <thead><tr><th>Properties</th><th>Results</th></tr></thead>
    <tbody>
  <!--  <tr><td>Number of distinct subjects</td>
        <td id="sdCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
    <tr><td>Number of distinct predicates</td>
        <td id="pdCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
    <tr><td>Number of distinct objects</td>
        <td id="odCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr> -->
     <tr><td>Number of used properties</td>
        <td id="pdCount"><img src="img/loadstat.gif" alt="loading ..."/></td></tr>
      <tr><td>Properties and total usage</td></tr>
        <tr><td id="pie3"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
     <tr><td>Property usage deviation by class</td></tr>
        <tr><td id="barDev"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
          </tbody>
    </table>
    
 <!--    <table class="table">
        <thead><tr><th>Live charts</th></tr></thead>
    <tbody>
        <tr><td>Predicates and total number of triples</td></tr>
        <tr><td id="pie3"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
        <tr><td>Predicate domains vs. total number of triples</td></tr>
        <tr><td id="pie1"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
        <tr><td>Subject domains vs. number of distinct subject</td></tr>
        <tr><td id="pie2"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
        <tr><td>Literal datatypes</td></tr>
        <tr><td id="bar1"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
        <tr><td>Property deviation</td></tr>
        <tr><td id="barDev"><img src="img/loadpie.gif" alt="loading ..."/></td></tr>
    </tbody>
    </table> -->
    <div id="error"></div>
</div>
</body>
</html>
